package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.demo.dto.Result;
import com.demo.dto.UserUpdateDTO;
import com.demo.entity.User;
import com.demo.mapper.UserMapper;
import com.demo.service.LoginService;
import com.demo.service.UploadService;
import com.demo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.utils.UserHolder;
import com.demo.vo.UserVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.demo.utils.SystemConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2022-03-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    LoginService loginService;

    @Resource
    UploadService uploadService;

    @Override
    public Result<UserVO> put(UserUpdateDTO userUpdateDTO, HttpServletRequest request) {
        User user = BeanUtil.copyProperties(userUpdateDTO, User.class);
        Integer userId = UserHolder.getUser().getUserId();
        user.setUserId(userId);
        updateById(user);
        // 修改完后还要更新redis中存放的用户信息
        // 先获取token
        String token = request.getHeader("authorization");
        // 获取修改后的user
        User updatedUser = getById(userId);
        // 保存到redis中
        loginService.setUserInfoToRedis(updatedUser, token);
        UserVO userVO = BeanUtil.copyProperties(updatedUser, UserVO.class);
        return Result.ok(userVO,"修改信息成功！");
    }

    @Override
    public Result<UserVO> detailData() {
        Integer userId = UserHolder.getUser().getUserId();
        UserVO userVO = baseMapper.getUserDetailData(userId);
        return Result.ok(userVO, "详细信息查询成功");
    }

    public String getNewAvatarFileDirName(String originalFilename) {
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        String newFileName = UUID.randomUUID().toString() + "." + suffix;
        Integer userId = UserHolder.getUser().getUserId();
        return UPLOAD_DIR + AVATAR_DIR + userId + "/" + newFileName;
    }

    @Override
    public Result<UserVO> uploadAvatar(MultipartFile image) {
        // 上传图片
        String newFileDirName = getNewAvatarFileDirName(image.getOriginalFilename());
        String uploadUrl = uploadService.uploadImage(image, newFileDirName).getData();
        // 更新用户信息
        Integer userId = UserHolder.getUser().getUserId();
        update().eq("user_id", userId)
                .set("avatar", uploadUrl).update();
        return Result.ok(BeanUtil.copyProperties(getById(userId), UserVO.class));
    }
}
